# 非阻塞IO
import socket


def run():
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client.setblocking(False)  # 将阻塞的方法设置为非阻塞的方法

    host = "www.baidu.com"

    try:
        client.connect((host, 80))
    except BlockingIOError as e:
        # 做一些其他的事情
        pass

    while 1:
        try:
            send_txt = "GET {} HTTP/1.1\r\nHost:{}\r\nConnection:close\r\n\r\n"
            client.send(send_txt.format("/", host).encode("utf8"))
            print("send success")
            break
        except OSError as e:
            pass

    data = b""
    while 1:
        try:
            d = client.recv(1024)  # 一个阻塞的方法，每次读取1024个字节
        except BlockingIOError as e:
            continue
        if d:
            data += d
        else:
            break

    data = data.decode("utf8")
    print(data)


if __name__ == '__main__':
    run()
